import {
    Card,
    Breadcrumb,
    Form,
    Button,
    Radio,
    Input,
    Upload,
    Space,
    Select, message
} from "antd"
import { PlusOutlined } from "@ant-design/icons"
import { Link, useNavigate, useSearchParams } from "react-router-dom"
import "./Publish.css"
import ReactQuill from "react-quill"
import "react-quill/dist/quill.snow.css"
import { useEffect, useState } from "react"
import { getArticleById, postArticle, updateArticleById } from "@/api/article.js"
import { useChannel } from "@/hooks/useChannel.js"


const { Option } = Select

export default function Publish() {
    const { channelsList } = useChannel()

    // 提交表单,新增文章
    const navigate = useNavigate()
    const onFinishForm = (values) => {
        if (imageList.length !== imageType) return message.warning("封面类型和图片数量不匹配")
        const dataForm = {
            title: values.title,
            content: values.content,
            cover: {
                type: imageType,
                images: imageList.map(item => {
                    if (item.response){
                        return item.response.data.url
                    }else {
                        return item.url
                    }
                })
            },
            channel_id: values.channel_id
        }
        if (articleId){
            updateArticleById({ ...dataForm, id: articleId })
        }else {
            postArticle(dataForm)
        }
        message.success(articleId ? "更新文章成功！" : "发布文章成功")
        setTimeout(() => {
            navigate("/article")
        }, 1500)
    }
    // 上传图片
    const [imageList, setImageList] = useState([])
    const onChangeUpload = (values) => {
        setImageList(values.fileList)
    }

    // 选择图片类型
    const [imageType, setImageType] = useState(0)
    const onTypeChange = (e) => {
        setImageType(e.target.value)
        // 防止在点击三图之后，切换单图或无图时出现图片数量和封面类型不匹配的情况
        setImageList([])
    }
    // 回显数据
    // 获取查询参数
    const [params] = useSearchParams()
    const articleId = params.get("id")
    // 获取form实例
    const[form] = Form.useForm()
    useEffect(() => {
        const getArticle = async () => {
            const res = await getArticleById(articleId)
            // 调用form表单的实例方法，进行数据回显
            const data = res.data.data
            const { cover } = data
            form.setFieldsValue({
                ...data,
                type: cover.type
            })
            // 显示图片列表
            setImageType(cover.type)
            // 显示图片
            setImageList(cover.images.map(url => {
                return { url }
            }))
        }
        if (articleId){
            getArticle()
        }
    }, [articleId, form])

    return (
      <div className="publish-container">
          <div className="publish">
              <Card
                title={
                    <Breadcrumb items={[
                        { title: <Link to={"/"}>首页</Link> },
                        { title: articleId ? "编辑文章" : "发布文章" }
                    ]}
                    />
                }
              >
                  <Form
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 16 }}
                    initialValues={{ type: imageType }}
                    onFinish={onFinishForm}
                    form={form}
                  >
                      <Form.Item
                        label="标题"
                        name="title"
                        rules={[{ required: true, message: "请输入文章标题" }]}
                      >
                          <Input placeholder="请输入文章标题" style={{ width: 400 }} />
                      </Form.Item>
                      <Form.Item
                        label="频道"
                        name="channel_id"
                        rules={[{ required: true, message: "请选择文章频道" }]}
                      >
                          <Select placeholder="请选择文章频道" style={{ width: 400 }}>
                              {channelsList.map(item => <Option key={item.id} value={item.id}>{item.name}</Option>)}
                          </Select>
                      </Form.Item>
                      <Form.Item label="封面">
                          <Form.Item name="type">
                              <Radio.Group onChange={onTypeChange}>
                                  <Radio value={0}>无图</Radio>
                                  <Radio value={1}>单图</Radio>
                                  <Radio value={3}>三图</Radio>
                              </Radio.Group>
                          </Form.Item>
                          {imageType > 0 && <Upload
                            name={"image"}
                            listType="picture-card"
                            showUploadList
                            action={"http://geek.itheima.net/v1_0/upload"}
                            onChange={onChangeUpload}
                            maxCount={imageType}
                            fileList={imageList}
                          >
                              <div style={{ marginTop: 8 }}>
                                  <PlusOutlined />
                              </div>
                          </Upload>
                          }

                      </Form.Item>
                      <Form.Item
                        label="内容"
                        name="content"
                        rules={[{ required: true, message: "请输入文章内容" }]}
                      >
                          {/*富文本编辑器*/}
                          <ReactQuill
                            className="publish-quill"
                            theme="snow"
                            placeholder="请输入文章内容"
                          />
                      </Form.Item>

                      <Form.Item wrapperCol={{ offset: 4 }}>
                          <Space>
                              <Button size="large" type="primary" htmlType="submit">
                                  {articleId ? "更新文章" : "发布文章"}
                              </Button>
                          </Space>
                      </Form.Item>
                  </Form>
              </Card>
          </div>
      </div>
    )
}